package com.lkm.market2_0.netapi;

import android.os.SystemClock;

import com.lkm.frame.P;
import com.lkm.frame.task.StopAble;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.DateHelp;
import com.lkm.javatool.ServerTimeSync;
import com.lkm.javatool.lang.NameValueP;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;





public class HttpRequest {


//        System.out.println(getString(null, "https://dev.balance.api.satrace.cn/", new NameValueP[]{



public static void VOID(){}
    public static String getApiInfo(String url, NameValueP[] params){
        String logParam = "";
        if (params != null) {
            for (NameValueP n : params) {
                if (n != null && n.getName() != null && n.getValue() != null)
                    logParam += "&" + n.getName() + "=" + n.getValue();
            }

        }
        String apiInfo=url + logParam;
        return apiInfo;
    }
    public static String sentContent(  String url, String content, StopAble sa) {

        String resulrStr = null;
        try {

            RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),content);

            Request.Builder requestBuilder = new Request.Builder().url(url);

            requestBuilder.post(body);

            Request request = requestBuilder.build();


            final Call call = getHttpClient().newCall(request);
            if (sa != null) {
                final Runnable oldCancelRun = sa.getCancelObserver();
                sa.setCancelObserver(new Runnable() {
                    @Override
                    public void run() {
                        if (oldCancelRun != null)
                            oldCancelRun.run();
                        call.cancel();
                    }
                });
            }

            Response response = call.execute();

            try {
                resulrStr = response.body().string();
            } catch (Exception e) {
                resulrStr = null;
                e.printStackTrace();
            }

        } catch (Exception e) {
            resulrStr = null;
            e.printStackTrace();

        }
        return resulrStr;
    }
    

    public static String getString(  String url, NameValueP[] params,NameValueP[] head, StopAble sa) {



        String resulrStr = null;
        try {

            FormEncodingBuilder feb = null;

            if (params != null) {
                feb = new FormEncodingBuilder();
                for (NameValueP n : params) {
                    if (n != null && n.getName() != null && n.getValue() != null)
                        feb.add(n.getName(), n.getValue());
                }
            }


            RequestBody body = null;
            try {
                if (feb != null)
                    body = feb.build();
            } catch (Exception e) {
                body = null;
            }
            feb = null;
            Builder requestBuilder = new Builder().url(url);

            requestBuilder.post(body);

            if(!CollectionHelp.isEmpty(head)){
                for (int i = 0; i < head.length; i++) {
                    NameValueP n = head[i];
                    if (n != null && n.getName() != null && n.getValue() != null)
                        requestBuilder.addHeader(head[i].getName(),head[i].getValue());
                }
            }

            Request request = requestBuilder.build();


            final Call call = getHttpClient().newCall(request);
            if (sa != null) {
                final Runnable oldCancelRun = sa.getCancelObserver();
                sa.setCancelObserver(new Runnable() {
                    @Override
                    public void run() {
                        if (oldCancelRun != null)
                            oldCancelRun.run();
                        call.cancel();
                    }
                });
            }

            
            long requestTime= SystemClock.uptimeMillis();

            Response response = call.execute();

//			for (Certificate certificate : response.handshake().peerCertificates()) {
//				System.out.println(CertificatePinner.pin(certificate));

            try {
                String servertime= response.header("servertime");

                try {
                    long timeInMillis = DateHelp.parseStrToTimeInMillis(servertime);
                    long curTime = SystemClock.uptimeMillis();
                    ServerTimeSync.getInstance().setNetLoadServerTime(curTime - requestTime, System.currentTimeMillis(), timeInMillis);
                    if(P.isDebug()){
                        P.p("=====服务器时间"+servertime);
                        P.p("=====ServerTimeSync "+ServerTimeSync.getInstance().getServerCurTime());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                resulrStr = response.body().string();
            } catch (Exception e) {
                resulrStr = null;
                e.printStackTrace();
            }

        } catch (Exception e) {
            resulrStr = null;
            e.printStackTrace();

        }

        if(P.isDebug())
        P.p(getApiInfo(url, params) +resulrStr);

        return resulrStr;
    }


    static {


//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.1.28", 8080));






//            setCertificates(Config.instance.getHttpsCertificates());





//                        .add("dev.balance.api.satrace.cn", "sha1
////                        .add("dev.balance.api.satrace.cn", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
////                        .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
////                        .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")


    }

    public static synchronized void clearCookie() {
        ((CookieManager) getHttpClient().getCookieHandler()).getCookieStore().removeAll();
    }


    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }


    public static void setCertificates(InputStream... certificates) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

                try {
                    if (certificate != null)
                        certificate.close();
                } catch (IOException e) {
                }
            }

            SSLContext sslContext = SSLContext.getInstance("TLS");

            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            trustManagerFactory.init(keyStore);
            sslContext.init
                    (
                            null,
                            trustManagerFactory.getTrustManagers(),
                            new SecureRandom()
                    );
            getHttpClient().setSslSocketFactory(sslContext.getSocketFactory());


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static OkHttpClient client = new OkHttpClient();

    static {
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        client.setCookieHandler(cookieManager);
        client.setConnectTimeout(30, TimeUnit.SECONDS);
        client.setReadTimeout(100, TimeUnit.SECONDS);
        client.setWriteTimeout(100, TimeUnit.SECONDS);



//        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

    }

    public static OkHttpClient getHttpClient() {
        if (client.getCache() == null) {
            //P.d("=====client.getCache()==null");
            
//			client.setCache(new Cache(new File(Config.getHttpFileCache(MyApplicationBase.application)), 1024 * 1024 * 20));
        }
        return client;

    }

}
